package logic

import (
	"context"

	"github.com/iriver/ai-offer/backend/internal/model"
	"github.com/iriver/ai-offer/backend/internal/svc"
	"github.com/iriver/ai-offer/backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
)

type ListUsersLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewListUsersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListUsersLogic {
	return &ListUsersLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListUsersLogic) ListUsers(req *types.ListUserRequest) (resp *types.UserListResponse, err error) {
	if req.Page < 1 {
		req.Page = 1
	}
	if req.PageSize < 1 || req.PageSize > 100 {
		req.PageSize = 20
	}

	// 计算分页偏移量
	offset := (req.Page - 1) * req.PageSize

	// 查询用户列表
	var users []*model.UserModel
	var total int64
	var err1 error

	query := l.svcCtx.DB.Model(&model.UserModel{})

	// 如果有角色筛选条件
	if req.Role != "" {
		query = query.Where("role = ?", req.Role)
	}

	// 查询总数
	err1 = query.Count(&total).Error
	if err1 != nil {
		l.Logger.Errorf("查询用户总数失败: %v", err1)
		return nil, httpx.NewCodeError(types.ErrDatabase, "查询用户列表失败")
	}

	// 查询列表数据
	err1 = query.Order("created_at DESC").
		Limit(int(req.PageSize)).
		Offset(int(offset)).
		Find(&users).Error
	if err1 != nil {
		l.Logger.Errorf("查询用户列表失败: %v", err1)
		return nil, httpx.NewCodeError(types.ErrDatabase, "查询用户列表失败")
	}

	// 组装响应数据
	resp = &types.UserListResponse{
		Total: total,
		List:  make([]types.UserResponse, 0, len(users)),
	}

	// 转换为响应模型
	for _, user := range users {
		resp.List = append(resp.List, types.UserResponse{
			Id:        user.ID,
			Email:     user.Email,
			Name:      user.Name,
			AvatarUrl: user.AvatarUrl,
			Role:      user.Role,
			CreatedAt: user.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt: user.UpdatedAt.Format("2006-01-02 15:04:05"),
		})
	}

	return resp, nil
}
